package com.qianfeng.zhangwei.extras.meilishuo;

import android.text.TextUtils;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.etsy.android.grid.StaggeredGridView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshStaggeredGridView;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.qianfeng.zhangwei.extras.R;
import com.qianfeng.zhangwei.extras.acitivity.BaseActivity;
import com.qianfeng.zhangwei.extras.meilishuo.adapter.AutoImagePageAdapter;
import com.qianfeng.zhangwei.extras.meilishuo.adapter.PtrStaggerAdapter;
import com.qianfeng.zhangwei.extras.meilishuo.auto.AutoScrollViewPager;
import com.qianfeng.zhangwei.extras.meilishuo.bean.AppBean;
import com.qianfeng.zhangwei.extras.meilishuo.bean.Banner;
import com.qianfeng.zhangwei.extras.meilishuo.bean.BannerSupper;
import com.qianfeng.zhangwei.extras.meilishuo.bean.Shop;
import com.qianfeng.zhangwei.extras.meilishuo.utils.HttpTools;
import com.qianfeng.zhangwei.extras.utils.UrlConstants;

import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.List;

/**
 *
 */
@EActivity(R.layout.activity_buy)
public class BuyActivity extends BaseActivity implements PullToRefreshBase.OnRefreshListener<StaggeredGridView>, AbsListView.OnScrollListener, AdapterView.OnItemClickListener {
    private BitmapUtils bitmapUtils;
    /**
     * 自定义下拉刷新瀑布流
     */
    @ViewById
    PullToRefreshStaggeredGridView ptrsgv;

    private ArrayList<Shop> shops = new ArrayList<>();
    private PtrStaggerAdapter adapter;

    private HttpHandler<String> giftHandler, bannerHandler;
    private int offset = 0;
    private int limit = 30;

    private StaggeredGridView staggeredGridView;
    private ViewHolder vh;


    /**
     * 指定解析泛型类型
     */
    TypeReference<AppBean<Shop>> type = new TypeReference<AppBean<Shop>>() {
    };
    /**
     * 是否清除数据
     */
    private boolean isClear;

    @Override
    public void inject() {
        bitmapUtils = new BitmapUtils(this);
        bitmapUtils.configDefaultLoadFailedImage(R.mipmap.ic_launcher);
        bitmapUtils.configDefaultLoadingImage(R.mipmap.ic_launcher);
    }

    @Override
    public void initView() {
        initHeadView();
        initShopUi();


    }

    /**
     * 初始化headview
     */
    private void initHeadView() {
        View view = getLayoutInflater().inflate(R.layout.item_head_layout, null);
        vh = new ViewHolder(view);
    }

    @Override
    protected void onResume() {
        super.onResume();
        vh.autoScrollViewPager.startAutoScroll();
    }

    @Override
    protected void onPause() {
        super.onPause();
        vh.autoScrollViewPager.stopAutoScroll();
    }

    /**
     * 初始化瀑布流控件相关参数
     */
    private void initShopUi() {
        ptrsgv.setMode(PullToRefreshBase.Mode.BOTH);
        ptrsgv.setOnRefreshListener(this);
        staggeredGridView = ptrsgv.getRefreshableView();
        staggeredGridView.setOnScrollListener(this);
        staggeredGridView.addHeaderView(vh.itemView);
        adapter = new PtrStaggerAdapter(shops, this, bitmapUtils);
        staggeredGridView.setAdapter(adapter);
    }

    @Override
    public void initData() {
        initBannerData();
        initShopData();
    }

    /**
     * 加载广告栏数据
     */
    private void initBannerData() {
        bannerHandler = new HttpUtils().send(HttpRequest.HttpMethod.GET, UrlConstants.LIWUSHUO_BANNERS_URL, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                BannerSupper bs = JSONObject.parseObject(responseInfo.result, BannerSupper.class);
                if (bs != null && bs.getCode() == 200 && !TextUtils.isEmpty(bs.getMessage())) {
                    vh.autoImagePageAdapter.notifyDataSetChanged(bs.getData().getBanners());
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {

            }
        });
    }


    private void initShopData() {
        giftHandler = HttpTools.getInstance().getDataFromServer(UrlConstants.MEILISHUO_SELECT_GET_URL, adapter, shops, ptrsgv, isClear, type);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        giftHandler.cancel();
        bannerHandler.cancel();
    }

//    @Override
//    public void onPullDownToRefresh(PullToRefreshBase<StaggeredGridView> refreshView) {
//        isClear = true;
//        offset = 0;
//        limit = 30;
//        initShopData();
//    }
//
//    @Override
//    public void onPullUpToRefresh(PullToRefreshBase<StaggeredGridView> refreshView) {
//        isClear = false;
//        offset = limit + 1;
//        limit += limit;
//        initShopData();
//
//
//
//    }

    /**
     * @return
     */
    public RequestParams getRequestParams() {
        RequestParams requestParams = new RequestParams();
        requestParams.addBodyParameter("r", "navigation-left%3Apos%3D1%3Aname%3D%25E7%25B2%25BE%25E9%2580%2589");
        requestParams.addBodyParameter("offset", String.valueOf(offset));
        requestParams.addBodyParameter("limit", String.valueOf(limit));
        requestParams.addBodyParameter("imei", "000000000000000");
        requestParams.addBodyParameter("mac", "08%3A00%3A27%3A9d%3A00%3A06&qudaoid=10008");
        requestParams.addBodyParameter("access_token", "d2b3fb04fb95f3b7b617a99d659c66e0");
        requestParams.addBodyParameter("device_id", "mac_08%3A00%3A27%3A9d%3A00%3A06");
        requestParams.addBodyParameter("st", "1435712726");
        requestParams.addBodyParameter("_sign", "b15fc85c64153aa9ab77a14d600e6ac7e4294777");
        return requestParams;
    }

    /**
     * @param view
     * @param position
     * @param id
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//       int currentPostion =  position-2;
    }

    @Override
    public void onRefresh(PullToRefreshBase<StaggeredGridView> refreshView) {
        isClear = true;
        offset = 0;
        limit = 30;
        initShopData();
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    private boolean mHasRequestedMore;

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

        if (!mHasRequestedMore) {
            int lastInScreen = firstVisibleItem + visibleItemCount;
            if (lastInScreen >= totalItemCount) {
                //加载事件
                onLoadMoreItems();
            }
        }
    }

    private void onLoadMoreItems() {
        isClear = false;
        offset = limit + 1;
        limit += limit;
        initShopData();
    }


    /**
     * headView
     */
    private class ViewHolder {
        private AutoScrollViewPager autoScrollViewPager;
        private AutoImagePageAdapter autoImagePageAdapter;
        private View itemView;
        private LinearLayout dotLayout;


        private List<Banner> imgUrls = new ArrayList<>();

        public ViewHolder(View itemView) {
            this.itemView = itemView;
            this.autoScrollViewPager = (AutoScrollViewPager) itemView.findViewById(R.id.auto_viewpger);
            dotLayout = (LinearLayout) itemView.findViewById(R.id.auto_dot_layout);
            autoImagePageAdapter = new AutoImagePageAdapter(imgUrls, BuyActivity.this, dotLayout, bitmapUtils);
            autoScrollViewPager.setOnPageChangeListener(autoImagePageAdapter);
            autoScrollViewPager.setAdapter(autoImagePageAdapter);
        }
    }


}
